#include "ssdsim_global.h"
#include "ssdsim_cache.h"
#include <cstdio>
#include <cstdlib>
#include "ssdsim.h"
#include <map>
void Simulator::read_trace_file(FILE* tracefile, ioreq_event *curr){
	int result;
	if((result = fscanf(tracefile, "%lf %d %d %d %d\n", &curr->time, &curr->devno, &curr->blkno, &curr->bcount, &curr->operation)) != 5) {
		if(result == EOF){
			curr->type = SIMULATION_STOP;
			return;
		}
		else {
			printf("Wrong number of arguments for I/O trace event type\n");
			return;
		}
	}

	curr->type = IO_CACHE_REQUEST;
	curr->next = NULL;
}

Simulator::Simulator(int argc, char **argv){
	cout << "ssdsim initialing begin" << endl;



	if((outfile = fopen("ssdsim.out", "w")) == NULL){
		printf("out file open error");
		exit(1);
	}

	if((tracefile = fopen(argv[1],"r")) == NULL){
			printf("trace file open error");
			exit(1);
	}
	request_queue = new ioreq_event();
	request_queue->next = NULL;
	request_queue->prev = NULL;

	cache_dev = new Cache_dev(CACHE_SIZE, outfile);

	cout << "ssdsim initialing end" << endl;
}

//void quit_simulation(){
//	if(io_event_queue != NULL)
//		free(io_event_queue);
//	if(ssdsim != NULL)
//		free(ssdsim);
//}

//void insert_io_event(ioreq_event * event){
//	ioreq_event * q = io_event_queue->next;
//	while(q){
//		if(q->time > event->time){
//			event->next = q->next;
//			q->next = event;
//			event->prev = q;
//			break;
//		}
//		q = q->next;
//	}
//}
//
//
ioreq_event * Simulator::get_ioevent(){
	ioreq_event *event;
	if(request_queue->next == NULL){
		event = new ioreq_event();
		read_trace_file(tracefile, event);
	}else{
		event = request_queue->next;
		request_queue->next = event->next;
	}

	return event;
}
//void send_cache_request(ioreq_event* curr){
//	send_io_cache(curr);
//}
//
//double send_io_ssd(ioreq_event* curr){
//	double delay = 2.0;
//	return delay;
//}
//void send_io_request(ioreq_event* curr){
//	double delay = send_io_ssd(curr);
//
////	update_ssdsim_stat(delay);
//}

//void update_ssdsim_stat(double delay){
//	ssdsim->acculate_delay += delay;
//	ssdsim->request_num++;
//}
void Simulator::run(){
	ioreq_event *curr;
	int event_count = 0, debug;
	cout << "ssdsim start running" << endl;
	while(TRUE){
		curr = get_ioevent();
		event_count++;
		if(event_count > 322875){
			debug++;
		}
		current_time = curr->time;

		if(curr->type == SIMULATION_STOP)
			break;
		else if(curr->type == IO_CACHE_REQUEST){
			cache_dev->send_cache_request(curr);
		}else if(curr->type == IO_SEVERCE_REQUEST){
			//cache_dev->send_io_request(curr);
		}else if(curr->type == IO_COMPLETION){

		}
		cout << event_count << endl;
	}
	cout << "ssdsim ended" << endl;
}


int main(int argc, char **argv){
//	Simulator ssdsim(argc, argv);
//	ssdsim.run();
	int a,b;
	while(EOF != scanf("%d %d",&a, &b)){
		printf("%d 1",a);
	}
	return 0;
}
